package alarm

import (
	"context"
	"time"

	"device-admin/config/mysql"
	"device-admin/internal/models"

	db_sharding "192.168.1.75/go-pkg/db-sharding"
	"192.168.1.75/go-pkg/errorx"
	"192.168.1.75/go-pkg/helper"
)

// AddAlarmNotifyRecord 批量增加告警通知记录
func AddAlarmNotifyRecord(records []models.AlarmNotifyRecord) ([]string, error) {
	// 判定告警记录条数
	if len(records) <= 0 {
		return []string{}, errorx.New("告警记录不能为空", -1)
	}

	// 增加主键id
	ids := []string{}
	for k := range records {
		uuid, err := helper.UUID{}.String()
		if err != nil {
			return []string{}, err
		}
		records[k].ID = uuid
		ids = append(ids, uuid)
	}

	dbs := db_sharding.GetDB(context.Background(), mysql.NewDB(), models.AlarmNotifyRecordTpl{}, time.Now().Unix(), time.Now().Unix())
	// 批量插入到数据库
	count := dbs.WriteDB.
		Create(&records).
		RowsAffected

	// 返回插入结果
	if count > 0 {
		return ids, nil
	} else {
		return []string{}, errorx.New("新增失败")
	}
}

// SyncAlarmSetting 同步告警通知设置
func SyncAlarmSetting(records []models.AlarmSetting) error {
	db := mysql.NewDB()
	if len(records) <= 0 {
		return errorx.New("告警设置记录不能为空")
	}
	for _, record := range records {
		var oldRecords models.AlarmSetting
		rowsAffected := db.Model(&models.AlarmSetting{}).Where(models.AlarmSetting{
			RobotID:   record.RobotID,
			AlarmType: record.AlarmType,
		}).Take(&oldRecords).RowsAffected
		// 不存在时创建
		if rowsAffected == 0 {
			db.Model(&models.AlarmSetting{}).Create(&record)
			// 存在时，更新
		} else if rowsAffected == 1 && oldRecords.Setting != record.Setting {
			db.Model(&models.AlarmSetting{}).Where(models.AlarmSetting{
				RobotID:   record.RobotID,
				AlarmType: record.AlarmType,
			}).Updates(&records)
		}
	}
	return nil
}

// AlarmSettingRecords 获取告警设置记录
func AlarmSettingRecords(robotID string) (interface{}, int64, error) {
	var alarmSetting []models.AlarmSetting
	total := mysql.NewDB().Model(&models.AlarmSetting{}).
		Where("robot_id = ?", robotID).
		Find(&alarmSetting).
		RowsAffected
	return alarmSetting, total, nil
}
